﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class BUserCoM : INTPage
{
    public int rowNo = 0;
    UserCoModel model = new UserCoModel();
    CommonMethod comHelp = new CommonMethod();
    UserCoDAO comm = new UserCoDAO();

    protected void Page_Load(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl2);

        if (!IsPostBack)
        {
            //权限
            comHelp.GetRight(this, new string[] { Session["UserCode"].ToString(), Session["CoCode"].ToString(), "BUserCo" },
                Grv, new string[] { "cmdAdd", "cmdEdit" }, new int[] { 7, 8 }, CommonModel.loginOut2);
            bind();
        }
    }
    // 绑定
    protected void bind()
    {
        DataTable[] dt = comm.GetUserCoInti();
        // GridView 绑定
        Grv.DataSource = dt[0];
        Grv.DataBind();
        //用户列表绑定
        ddlUser.DataSource = dt[1];
        ddlUser.DataValueField = "UserCode";
        ddlUser.DataTextField = "UserName";
        ddlUser.DataBind();
        this.ddlUser.Items.Add(new ListItem("请选择 (Please Select)", "0"));
        //公司绑定
        ddlCo.DataSource = dt[2];
        ddlCo.DataValueField = "CoCode";
        ddlCo.DataTextField = "CoName";
        ddlCo.DataBind();
        this.ddlCo.Items.Add(new ListItem("请选择 (Please Select)", "0"));
    }
          
    // 换页
    protected void Grv_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            Grv.PageIndex = e.NewPageIndex;
            cmdSelect_Click(sender, e);//数据绑定
        }
        catch
        {
        }
    }
    // GridView 行事件
    protected void Grv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        rowNo++;
        //鼠标经过事件
        if (e.Row.RowIndex != -1)
        {
            //设置悬浮鼠标指针形状为"小手"
            e.Row.Attributes["style"] = "Cursor:hand";
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "lastColor=this.style.backgroundColor;this.style.backgroundColor='#CCCC99';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=lastColor;");
                if ("zh-cn".Equals(Session["Language"].ToString()))
                {
                    ((LinkButton)e.Row.Cells[8].Controls[0]).Attributes.Add("onclick", "return confirm('确实要删除？');");
                }
                else
                {
                    ((LinkButton)e.Row.Cells[8].Controls[0]).Attributes.Add("onclick", "return confirm('OK to delete?');");
                }
            }
        }
    }

    // GridView 删除
    protected void Grv_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        model.CoCode = Grv.Rows[e.RowIndex].Cells[3].Text.ToString();
        model.UserCode = Grv.Rows[e.RowIndex].Cells[1].Text.ToString();

        if (comm.DeleteUserCo(model) > 0)
        {
            bindGV("");
            setFlag(true);
            CommonMethod.regAlertMessage("操作成功-Success!", this);            
            txtDesc.Text = "";
            ddlUser.Focus();
        }
        else
        {
            CommonMethod.regAlertMessage("出现错误-Error!", this);
            ddlUser.Focus();
        }
    }
    // GridView
    protected void Grv_SelectedIndexChanged(object sender, EventArgs e)
    {
        setFlag(false);
        try
        {
            ddlUser.SelectedValue = Grv.Rows[Grv.SelectedIndex].Cells[1].Text.ToString();
            ddlCo.SelectedValue = Grv.Rows[Grv.SelectedIndex].Cells[3].Text.ToString();
        }
        catch { }
        txtDesc.Text = Grv.Rows[Grv.SelectedIndex].Cells[6].Text.ToString();
    }
    // 添加
    protected void cmdAdd_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl2);

        model.CoCode = ddlCo.SelectedValue.ToString();
        model.UserCode = ddlUser.SelectedValue.ToString();
        model.UserCoDesc = txtDesc.Text.ToString();
        model.UpdateAuthor = Session["UserCode"].ToString();
        model.UpdateDate = System.DateTime.Now.ToString("yyyy-MM-dd hh:mm");

        if (comm.AddUserCo(model) > 0)
        {
            bindGV("");
            CommonMethod.regAlertMessage("操作成功-Success!", this);
            ddlUser.Focus();
        }
        else
        {
            CommonMethod.regAlertMessage("出现错误-Error!", this);
            ddlCo.Focus();
        }
    }
    // 编辑
    protected void cmdEdit_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl2);

        model.CoCode = ddlCo.SelectedValue.ToString();
        model.UserCode = ddlUser.SelectedValue.ToString();
        model.UserCoDesc = txtDesc.Text.ToString();
        model.UpdateAuthor = Session["UserCode"].ToString();
        model.UpdateDate = System.DateTime.Now.ToString("yyyy-MM-dd hh:mm");

        if (comm.EditUserCo(model) > 0)
        {
            bindGV("");
            setFlag(true);
            CommonMethod.regAlertMessage("操作成功-Success!", this);
           
            txtDesc.Text = "";
            ddlUser.Focus();
        }
        else
        {
            CommonMethod.regAlertMessage("出现错误-Error!", this);
            ddlCo.Focus();
        }
    }

    protected void ddlCo_SelectedIndexChanged(object sender, EventArgs e)
    {
        //string companyCode = ddlCo.SelectedValue;
        //DataTable dt = cs.GetDept(companyCode);
        //ddlDept.DataSource = dt;
        //ddlDept.DataValueField = "DepCode";
        //ddlDept.DataTextField = "DepName";
        //ddlDept.DataBind();
        //ListItem l_item = new ListItem("全部-ALL", "All");
        //this.ddlDept.Items.Insert(0, l_item);
    }
    
    
    protected void cmdClear_ServerClick(object sender, EventArgs e)
    {
        ddlCo.SelectedIndex = 0;
        ddlCo.Enabled = true;
        ddlUser.Enabled = true;
        ddlUser.SelectedIndex = 0;
        txtDesc.Text = "";
    }
    // 查询
    protected void cmdSelect_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl2);
        string selectSql = string.Empty;
        if (!ddlUser.SelectedValue.ToString().Equals("0"))
        {
            selectSql += string.Format("and UC.UserCode ='{0}'", ddlUser.SelectedValue);
        }
        if (!ddlCo.SelectedValue.ToString().Equals("0"))
        {
            selectSql += string.Format("and UC.CoCode ='{0}'", ddlCo.SelectedValue);
        }
        if (!string.IsNullOrEmpty(CommonMethod.ConvertSql(txtDesc.Text.Trim().ToString())))
        {
            selectSql += string.Format("and UC.UserCoDesc like '%{0}%'", CommonMethod.ConvertSql(txtDesc.Text.Trim().ToString()));
        }
        bindGV(selectSql);
    }
    //数据绑定的代码
    private void bindGV(string selectSql)
    {
        DataTable dt = comm.GetUserCoQuery(selectSql);
        Grv.DataSource = dt;
        Grv.DataBind();
        if (dt.Rows.Count > 0)
        {
            // 设置分页行永远显示
            Grv.BottomPagerRow.Visible = true;
            //赋值Label记录条数
            Label label1 = Grv.BottomPagerRow.FindControl("lblCount") as Label;
            label1.Text = dt.Rows.Count.ToString();
        }
    }
    //跳页事件
    protected void Grv_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "NewPage")
            {
                TextBox tb = Grv.BottomPagerRow.FindControl("txtNewPageIndex") as TextBox;
                int pageindex = Convert.ToInt32(tb.Text);
                Grv.PageIndex = pageindex - 1;
                cmdSelect_Click(sender, e);//数据绑定
            }
        }
        catch
        {
            CommonMethod.regAlertMessage("输入不合法-Error format!", this);
        }
    }

    private void setFlag(bool Flag)
    {
        bool Flag1 = false;
        if (!Flag)
        {
            Flag1 = true;
        }
        ddlUser.Enabled = Flag;
        cmdAdd.Enabled = Flag;
        cmdEdit.Enabled = Flag1;
    }
       
    //导出excel
    protected void cmdExport_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl2);
        try
        {
            string selectSql = string.Empty;
            if (ddlUser.SelectedIndex != 0)
            {
                selectSql += "and uc.UserCode ='" + ddlUser.SelectedValue + "' ";
            }
            if (ddlCo.SelectedIndex != 0)
            {
                selectSql += "and uc.CoCode ='" + ddlCo.SelectedValue + "' ";
            }
            if (!string.IsNullOrEmpty(CommonMethod.ConvertSql(txtDesc.Text.Trim().ToString())))
            {
                selectSql += "and uc.UserCoDesc like '%" + CommonMethod.ConvertSql(txtDesc.Text.Trim().ToString()) + "%' ";
            }
            DataTable dt = comm.GetUserCoQuery(selectSql);
            CreateExcel(ref dt, "UserCompany", "UserCompany");
            dt.Dispose();
            dt = null;
        }
        catch
        {
        }
    }
    //创建EXCEL
    public void CreateExcel(ref DataTable dt, string FileName, string title)
    {
        try
        {
            HttpResponse resp;
            resp = Page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-7");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName + ".xls");
            int i = 0;
            string[] colheader ={ "NO.", "员工编号", "用户名", "公司编号", "公司","描述" };
            DataRow[] myRow = dt.Select("");
            StringBuilder htmlTable = new StringBuilder();
            int colcount = dt.Columns.Count;
            htmlTable.Append("<html>");
            htmlTable.Append("<table style='border-color:Black;' border='1px'>");     //添加表格   
            htmlTable.Append("<tr>");
            for (int hcount = 0; hcount < colheader.Length; hcount++)
            {
                htmlTable.Append("<td align='center' style='font-size:12px;font-weight:bolder;font-family:宋体'>" + colheader[hcount]);
                htmlTable.Append("</td>");
            }
            htmlTable.Append("</tr>");
            int rowNumber = 0;

            foreach (DataRow row in myRow)
            {
                rowNumber++;
                htmlTable.Append("<tr>");
                htmlTable.Append("<td align='center' style='font-size:12px;font-weight:lighter;font-family:宋体'>" + Convert.ToString(rowNumber) + "</td>");
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName.Equals("BankAccount"))
                    { htmlTable.Append("<td align='left' style='font-size:12px;font-weight:lighter;font-family:宋体;vnd.ms-excel.numberformat:@\'>" + row[i].ToString()); }
                    else
                    { htmlTable.Append("<td align='left' style='font-size:12px;font-weight:lighter;font-family:宋体'>" + row[i].ToString()); }
                    htmlTable.Append("</td>");
                }
                htmlTable.Append("</tr>");
            }
            htmlTable.Append("</table>");
            htmlTable.Append("</html>");
            resp.Write(Convert.ToString(htmlTable));
            //写缓冲区中的数据到HTTP头文件中 
            resp.End();
        }
        catch { }
    }
}
